import {useNavigate, useParams} from "react-router-dom";
import {Badge, Button, Card, Divider, message, Popconfirm, Tag, Typography} from "antd";
import {
    ArrowLeftOutlined,
    CalendarOutlined,
    CheckCircleOutlined,
    CloudServerOutlined,
    CodeOutlined,
    DeleteOutlined,
    EditOutlined,
    FileTextOutlined,
    FormOutlined,
    GitlabOutlined,
    InfoCircleOutlined,
    UserOutlined
} from "@ant-design/icons";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import {useEffect, useState} from "react";
import ServiceBasicEdit from "../../../components/console/governance/serviceBasicEdit";
import ServiceConfigFileEdit from "../../../components/console/governance/serviceConfigFileEdit";

const {Title, Text, Paragraph} = Typography;

const ServiceGovernanceDetail = () => {
    const navigate = useNavigate();
    const [messageApi, contextHolder] = message.useMessage();
    const {operation, serviceGovernanceId} = useParams();
    const [loading, setLoading] = useState(true);

    // 编辑服务基本信息模态框开关
    const [editServiceBasicVisible, setEditServiceBasicVisible] = useState(false);
    // 编辑服务配置文件模态框开关
    const [editServiceConfigFileVisible, setEditServiceConfigFileVisible] = useState(false);

    const [serviceGovernanceDetail, setServiceGovernanceDetail] = useState({
        id: '',
        createdBy: '',
        createdTime: '',
        createdByUserNickname: '',
        lastModifiedBy: '',
        lastModifiedTime: '',
        lastModifiedByUserNickname: '',
        serviceName: '',
        serviceTitle: '',
        serviceDescription: '',
        serviceConfigFile: '',
        frontBackType: '',
        frontBackTypeValue: '', // 项目类型：前端/后端
        gitUrl: '',
        projectManager: '',
        projectManagerNickname: '',
        serviceHealthyInstances: []
    });

    /**
     * 根据id查询服务治理信息
     */
    const searchServiceGovernanceById = () => {
        setLoading(true);
        RequestUtils.post(RequestApis.serviceGovernance.searchById, {
            id: serviceGovernanceId
        }).then(res => {
            setServiceGovernanceDetail(res.data.data);
            setLoading(false);
        }).catch(err => {
            messageApi.error(err.message);
            setLoading(false);
        });
    };

    /**
     * 根据id移除服务治理信息
     */
    const removeServiceGovernanceById = () => {
        RequestUtils.post(RequestApis.serviceGovernance.removeById, {
            id: serviceGovernanceId
        }).then(res => {
            messageApi.success("删除服务信息成功，即将返回服务治理页面").then(() => {
                navigate('/console/governance');
            });
        }).catch(err => messageApi.error(err.message));
    }

    useEffect(() => {
        searchServiceGovernanceById();
        // eslint-disable-next-line
    }, []);

    const tagColorMap = {
        '后端': 'blue',
        '前端': 'purple'
    };

    // 通用卡片样式（增强边缘和阴影）
    const baseCardStyle = {
        marginBottom: '24px',
        borderRadius: '12px',
        border: '1px solid #e0e0e0', // 明显边框
        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)', // 加深阴影
        transition: 'all 0.3s ease' // 统一过渡效果
    };

    return (
        <div style={{padding: '24px', backgroundColor: '#ffffff'}}>
            {contextHolder}

            {/* 返回按钮区域 */}
            <div style={{marginBottom: '24px'}}>
                <div style={{width: '100%', display: 'flex', justifyContent: 'space-between'}}>
                    <Button
                        type="primary"
                        onClick={() => {
                            navigate('/console/governance');
                        }}
                        style={{
                            borderRadius: '20px',
                            padding: '6px 20px',
                            backgroundColor: '#1890ff',
                            borderColor: '#1890ff',
                            transition: 'all 0.3s ease',
                            display: 'inline-flex',
                            alignItems: 'center',
                            boxShadow: '0 2px 8px rgba(24, 144, 255, 0.2)',
                            width: '300px'
                        }}
                        hoverStyle={{
                            backgroundColor: '#096dd9',
                            boxShadow: '0 4px 16px rgba(24, 144, 255, 0.3)',
                            borderColor: '#096dd9'
                        }}
                    >
                        <ArrowLeftOutlined style={{marginRight: '6px'}}/>
                        返回服务治理页面
                    </Button>
                    {operation === 'edit' ?
                        <Popconfirm
                            placement="leftTop"
                            title={"删除服务信息确认"}
                            description={"确定要删除当前服务信息？删除后数据将无法恢复。"}
                            okText="确认"
                            cancelText="取消"
                            onConfirm={() => {
                                removeServiceGovernanceById();
                            }}
                        >
                            <Button
                                type="primary"
                                style={{
                                    borderRadius: '20px',
                                    padding: '6px 20px',
                                    backgroundColor: '#E83131',
                                    borderColor: '#E83131',
                                    transition: 'all 0.3s ease',
                                    display: 'inline-flex',
                                    alignItems: 'center',
                                    boxShadow: '0 2px 8px rgba(232, 49, 49, 0.2)',
                                    width: '340px'
                                }}
                                hoverStyle={{
                                    backgroundColor: '#c41d1d',
                                    boxShadow: '0 4px 16px rgba(232, 49, 49, 0.3)',
                                    borderColor: '#c41d1d'
                                }}
                            >
                                <DeleteOutlined style={{marginRight: '6px'}}/>
                                删除当前服务
                            </Button>
                        </Popconfirm>
                        : <div/>
                    }
                </div>
            </div>

            {/* 服务标题卡片 */}
            <Card
                style={baseCardStyle}
                loading={loading}
            >
                <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                    <div>
                        <Title level={2} style={{margin: 0, color: '#1f2329'}}>
                            {serviceGovernanceDetail.serviceTitle}
                        </Title>
                        <Text style={{color: '#6b7280', fontSize: '14px'}}>
                            服务ID: {serviceGovernanceDetail.id}
                        </Text>
                    </div>
                    <Badge
                        count={serviceGovernanceDetail.frontBackTypeValue}
                        size="large"
                        style={{
                            backgroundColor: tagColorMap[serviceGovernanceDetail.frontBackTypeValue] || '#1890ff',
                            borderRadius: '16px',
                            padding: '4px 12px',
                            fontSize: '14px',
                            display: 'inline-flex',
                            alignItems: 'center',
                            justifyContent: 'center'
                        }}
                    />
                </div>
            </Card>

            {/* 服务健康实例区域：根据项目类型差异化渲染 */}
            {serviceGovernanceDetail.frontBackTypeValue === '后端' ? (
                // 后端项目：展示服务健康实例卡片
                <Card
                    title={
                        <div style={{display: 'flex', alignItems: 'center', color: '#1f2329'}}>
                            <CloudServerOutlined style={{marginRight: '8px', color: '#52c41a'}}/>
                            服务健康实例
                            <Badge
                                count={serviceGovernanceDetail.serviceHealthyInstances?.length || 0}
                                style={{
                                    marginLeft: '10px',
                                    backgroundColor: '#52c41a',
                                    boxShadow: '0 2px 4px rgba(82, 196, 26, 0.2)'
                                }}
                            />
                        </div>
                    }
                    style={{
                        ...baseCardStyle,
                        borderLeft: '4px solid #52c41a' // 左侧特色边框，突出实例卡片
                    }}
                    loading={loading}
                >
                    {serviceGovernanceDetail.serviceHealthyInstances?.length > 0 ? (
                        <div style={{
                            display: 'grid',
                            gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
                            gap: '20px' // 增大间距，避免拥挤
                        }}>
                            {serviceGovernanceDetail.serviceHealthyInstances.map((item, index) => (
                                <Card
                                    key={index}
                                    style={{
                                        border: '1px solid #00cc66',
                                        borderRadius: '10px',
                                        overflow: 'hidden',
                                        background: 'linear-gradient(to bottom, #EEFFF4 0%, #F5FFF8 100%)', // 轻微渐变背景
                                        transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)' // 平滑过渡
                                    }}
                                    hoverStyle={{
                                        transform: 'translateY(-6px) scale(1.01)', // 上浮+轻微放大
                                        boxShadow: '0 12px 20px rgba(82, 196, 26, 0.15)', // 增强阴影
                                        borderColor: '#006633' // 边框变色
                                    }}
                                >
                                    <div style={{
                                        display: 'flex',
                                        justifyContent: 'space-between',
                                        alignItems: 'center',
                                        marginBottom: '12px',
                                        paddingBottom: '12px',
                                        borderBottom: '1px dashed #f0f0f0'
                                    }}>
                                        <div style={{display: 'flex', alignItems: 'center'}}>
                                            <div style={{
                                                backgroundColor: 'rgba(82, 196, 26, 0.15)',
                                                borderRadius: '50%',
                                                padding: '6px',
                                                marginRight: '10px'
                                            }}>
                                                <CheckCircleOutlined style={{color: '#52c41a', fontSize: '18px'}}/>
                                            </div>
                                            <Text strong style={{fontSize: '16px'}}>实例 {index + 1}</Text>
                                        </div>
                                        <Tag
                                            color="success"
                                            style={{
                                                borderRadius: '12px',
                                                padding: '3px 10px',
                                                fontSize: '13px',
                                                backgroundColor: 'rgba(82, 196, 26, 0.15)',
                                                color: '#52c41a',
                                                border: '1px solid #b7eb8f'
                                            }}
                                        >
                                            健康运行中
                                        </Tag>
                                    </div>

                                    <div style={{paddingTop: '12px'}}>
                                        <div style={{marginBottom: '12px', display: 'flex', alignItems: 'flex-start'}}>
                                            <Text style={{color: '#4e5969', width: '80px', flexShrink: 0}}>服务地址:</Text>
                                            <Text style={{
                                                fontSize: '14px',
                                                wordBreak: 'break-all',
                                                fontWeight: 500
                                            }}>{item.serviceAddress}</Text>
                                        </div>

                                        <div style={{display: 'flex', alignItems: 'flex-start'}}>
                                            <Text style={{color: '#4e5969', width: '80px', flexShrink: 0}}>IP类型:</Text>
                                            <Text
                                                style={{fontSize: '14px', fontWeight: 500}}
                                            >{item.registerIpTypeValue || item.registerIpType}</Text>
                                        </div>
                                    </div>
                                </Card>
                            ))}
                        </div>
                    ) : (
                        <div style={{
                            textAlign: 'center',
                            padding: '40px 0',
                            color: '#86909c',
                            backgroundColor: '#f7f8fa',
                            borderRadius: '8px',
                            border: '1px dashed #e0e0e0'
                        }}>
                            <CloudServerOutlined style={{fontSize: '40px', marginBottom: '16px', opacity: 0.5}}/>
                            <p>暂无服务健康实例信息</p>
                        </div>
                    )}
                </Card>
            ) : (
                // 前端项目：展示提示卡片（不展示实例）
                <Card
                    title={
                        <div style={{display: 'flex', alignItems: 'center', color: '#1f2329'}}>
                            <CloudServerOutlined style={{marginRight: '8px', color: '#fa8c16'}}/>
                            服务实例说明
                        </div>
                    }
                    style={{
                        ...baseCardStyle,
                        borderLeft: '4px solid #fa8c16' // 左侧特色边框，与前端类型配色呼应
                    }}
                    loading={loading}
                >
                    <div style={{
                        textAlign: 'center',
                        padding: '40px 20px',
                        color: '#4e5969',
                        backgroundColor: '#fff8f0',
                        borderRadius: '8px',
                        border: '1px dashed #ffe8cc'
                    }}>
                        <InfoCircleOutlined style={{
                            fontSize: '40px',
                            marginBottom: '16px',
                            color: '#fa8c16',
                            opacity: 0.8
                        }}/>
                        <p style={{fontSize: '15px', lineHeight: '1.6'}}>
                            当前为前端项目，暂不支持服务实例展示<br/>
                            服务注册是后端服务的概念，用于标识服务的在线节点状态
                        </p>
                    </div>
                </Card>
            )}

            {/* 基本信息卡片 */}
            <Card
                title={
                    <div style={{
                        display: 'flex',
                        alignItems: 'center',
                        color: '#1f2329',
                        justifyContent: 'space-between'
                    }}>
                        <div>
                            <InfoCircleOutlined style={{marginRight: '8px', color: '#1890ff'}}/>
                            <span>基本信息</span>
                        </div>
                        <div>
                            {operation === 'edit' ?
                                <Button
                                    color='purple'
                                    variant='solid'
                                    style={{width: '320px', marginRight: '10px'}}
                                    onClick={() => setEditServiceBasicVisible(true)}
                                >
                                    <FormOutlined/>
                                    编辑服务基本信息
                                </Button> :
                                <div/>
                            }
                        </div>
                    </div>
                }
                style={{
                    ...baseCardStyle,
                    borderLeft: '4px solid #1890ff' // 左侧特色边框，区分不同类型卡片
                }}
                loading={loading}
            >
                {/* 4列网格布局 */}
                <div style={{display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '24px 16px'}}>
                    {/* 第一行：服务名称、项目管理员、git地址、空项 */}
                    <div>
                        {/* 字段名+图标 */}
                        <div style={{display: 'flex', alignItems: 'center', marginBottom: '6px'}}>
                            <CodeOutlined style={{marginRight: '6px', color: '#1890ff', fontSize: '14px'}}/>
                            <Text strong style={{color: '#4e5969', fontSize: '14px'}}>服务名称</Text>
                        </div>
                        {/* 单独的值内容 */}
                        <Text style={{fontSize: '15px', color: '#1f2329'}}>{serviceGovernanceDetail.serviceName}</Text>
                    </div>

                    <div>
                        <div style={{display: 'flex', alignItems: 'center', marginBottom: '6px'}}>
                            <UserOutlined style={{marginRight: '6px', color: '#722ed1', fontSize: '14px'}}/>
                            <Text strong style={{color: '#4e5969', fontSize: '14px'}}>项目管理员</Text>
                        </div>
                        <div>
                            <Text style={{
                                fontSize: '15px',
                                color: '#1f2329'
                            }}>{serviceGovernanceDetail.projectManagerNickname}</Text>
                            <Text style={{
                                marginLeft: '6px',
                                color: '#86909c',
                                fontSize: '14px'
                            }}>({serviceGovernanceDetail.projectManager})</Text>
                        </div>
                    </div>

                    <div>
                        <div style={{display: 'flex', alignItems: 'center', marginBottom: '6px'}}>
                            <GitlabOutlined style={{marginRight: '6px', color: '#f5222d', fontSize: '14px'}}/>
                            <Text strong style={{color: '#4e5969', fontSize: '14px'}}>Git仓库地址</Text>
                        </div>
                        <Text
                            style={{fontSize: '15px', color: '#1890ff', wordBreak: 'break-all'}}
                            ellipsis={{rows: 2, expandable: true, symbol: '显示全部'}}
                        >
                            {serviceGovernanceDetail.gitUrl}
                        </Text>
                    </div>

                    {/* 第一行第4列空项 */}
                    <div></div>

                    {/* 第二行：创建人、创建时间、修改人、修改时间 */}
                    <div>
                        <div style={{display: 'flex', alignItems: 'center', marginBottom: '6px'}}>
                            <UserOutlined style={{marginRight: '6px', color: '#fa8c16', fontSize: '14px'}}/>
                            <Text strong style={{color: '#4e5969', fontSize: '14px'}}>创建人</Text>
                        </div>
                        <Text style={{
                            fontSize: '15px',
                            color: '#1f2329'
                        }}>{serviceGovernanceDetail.createdByUserNickname}</Text>
                    </div>

                    <div>
                        <div style={{display: 'flex', alignItems: 'center', marginBottom: '6px'}}>
                            <CalendarOutlined style={{marginRight: '6px', color: '#fa8c16', fontSize: '14px'}}/>
                            <Text strong style={{color: '#4e5969', fontSize: '14px'}}>创建时间</Text>
                        </div>
                        <Text style={{fontSize: '15px', color: '#1f2329'}}>{serviceGovernanceDetail.createdTime}</Text>
                    </div>

                    <div>
                        <div style={{display: 'flex', alignItems: 'center', marginBottom: '6px'}}>
                            <UserOutlined style={{marginRight: '6px', color: '#fa8c16', fontSize: '14px'}}/>
                            <Text strong style={{color: '#4e5969', fontSize: '14px'}}>最后修改人</Text>
                        </div>
                        <Text style={{
                            fontSize: '15px',
                            color: '#1f2329'
                        }}>{serviceGovernanceDetail.lastModifiedByUserNickname}</Text>
                    </div>

                    <div>
                        <div style={{display: 'flex', alignItems: 'center', marginBottom: '6px'}}>
                            <EditOutlined style={{marginRight: '6px', color: '#fa8c16', fontSize: '14px'}}/>
                            <Text strong style={{color: '#4e5969', fontSize: '14px'}}>最后修改时间</Text>
                        </div>
                        <Text style={{
                            fontSize: '15px',
                            color: '#1f2329'
                        }}>{serviceGovernanceDetail.lastModifiedTime}</Text>
                    </div>
                </div>

                <Divider style={{margin: '20px 0'}}/>

                <div>
                    <div style={{display: 'flex', alignItems: 'center', marginBottom: '8px'}}>
                        <InfoCircleOutlined style={{marginRight: '6px', color: '#1890ff', fontSize: '14px'}}/>
                        <Text strong style={{color: '#4e5969', fontSize: '14px'}}>服务描述</Text>
                    </div>
                    <Paragraph
                        style={{
                            fontSize: '15px',
                            lineHeight: '1.8',
                            padding: '12px',
                            backgroundColor: '#f7f8fa',
                            borderRadius: '8px',
                            margin: 0,
                            color: '#1f2329',
                            border: '1px solid #f0f0f0'
                        }}
                    >
                        {serviceGovernanceDetail.serviceDescription || '无描述信息'}
                    </Paragraph>
                </div>
            </Card>

            {/* 服务配置文件卡片 */}
            <Card
                title={
                    <div style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        color: '#1f2329'
                    }}>
                        <div>
                            <FileTextOutlined style={{marginRight: '8px', color: '#fa8c16'}}/>
                            服务配置文件
                        </div>
                        <div>
                            {
                                operation === 'edit' ?
                                    <Button
                                        color='pink'
                                        variant={'solid'}
                                        style={{width: '320px', marginRight: '20px'}}
                                        onClick={() => {
                                            setEditServiceConfigFileVisible(true);
                                        }}
                                    >
                                        <FormOutlined/>
                                        编辑服务配置文件
                                    </Button>
                                    : <div/>
                            }
                        </div>
                    </div>
                }
                style={{
                    ...baseCardStyle,
                    borderLeft: '4px solid #fa8c16' // 左侧特色边框，区分不同类型卡片
                }}
                loading={loading}
            >
                <div
                    style={{
                        backgroundColor: '#282c34',
                        color: '#abb2bf',
                        padding: '20px',
                        borderRadius: '8px',
                        fontSize: '14px',
                        lineHeight: '1.5',
                        whiteSpace: 'pre-wrap', // 保留换行和空格
                        fontFamily: 'SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace',
                        // 移除滚动相关设置，让内容高度自适应
                        border: '1px solid #383c44'
                    }}
                >
                    {serviceGovernanceDetail.serviceConfigFile || '无配置文件信息'}
                </div>
            </Card>

            {/* 编辑基本信息 */}
            <ServiceBasicEdit
                visible={editServiceBasicVisible}
                setVisible={setEditServiceBasicVisible}
                serviceDetail={serviceGovernanceDetail}
                searchServiceGovernanceById={searchServiceGovernanceById}
            />

            {/* 编辑配置文件 */}
            <ServiceConfigFileEdit
                visible={editServiceConfigFileVisible}
                setVisible={setEditServiceConfigFileVisible}
                serviceDetail={serviceGovernanceDetail}
                searchServiceGovernanceById={searchServiceGovernanceById}
            />
        </div>
    );
};

export default ServiceGovernanceDetail;